<?php
namespace app\common;

use think\Controller;
use think\Facade\Request;
use think\Session;
use think\Db;

use app\model\UserModel;
/*公共函数工具*/
use app\common\Tool\ApiErrDesc;
use app\common\Response\ResponseJson;
use app\common\Auth\JwtAuth;


// header('Access-Control-Allow-Origin:*');
// header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); // 允许option，get，post请求

// header('Access-Control-Allow-Headers:x-requested-with,superuserid,content-type,x-token');
//     // 允许x-requested-with请求头
// header('Access-Control-Allow-Credentials: true');

class BaseController extends Controller{



    use ResponseJson;
    protected $noNeedLogin=[
         'User/session_set'
    ];
    protected $user;
    protected $uid;
    private  $version = 'X.0.1';
    //token 验证
    public $jwtAuth =null;


    protected $beforeActionList = [
        'validtoken'=>'',
    ];


    // public function __construct()
    // {
    //     $this->jwtAuth = JwtAuth::getInstance();
    // }
    // public function _initialize(){
    //         $this->noNeedLogin = ['session_set',''];
    //     }
    /**
     * GNLEON
     * @HtttpRequest                        
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-08-31T17:26:53+0800
     * @LastTime     2020-08-31T17:26:53+0800
     * @return       [type]                   [description]
     */
    public function index(){
        echo "THINKPHP版本:".THINK__VERSION;
        echo "后台版本:".$this->version;
        echo "<div>接口说明文档:https://docs.apipost.cn/view/037be65f90520fbf </br></div>";
        echo "<div>
                <h1>依赖:</h1>
                <p>        
                topthink/framework</br>
                topthink/think-worker</br>
                yunpian/yunpian-php-sdk</br>
                aferrandini/phpqrcode</br>
                lcobucci/jwt</br>
                workerman(for-win/linux)</br>
                easywechat</br>
                </p>
            </div>";
        echo "<small>power by zsicp</small>";
        echo "<span>-</span>";
    }
    /**
     * token验证
     * @remark action 必须小写 大写驼峰 无法检测
     */
    protected function validtoken(){
        $this->jwtAuth = JwtAuth::getInstance();

        $this->cross();
        $action = Request::instance()->action();
        $controller = Request::instance()->controller();
        $method = $controller.'/'.$action;
   
        if(in_array($method,$this->noNeedLogin) ){
            return;
        } 
        $token = Request::instance()->header('token');
        // $token = empty($token)?Request::instance()->param('token'):$token;
        // $token = '89b266b6fdbdfa73d8e7e3aa5735e890ed5e917a';
        // var_dump($token);

        if(empty($token) ){
            echo json_encode(["message"=>"token不存在","code" => 400],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

            // return json_encode(['code' => $code, 'message' => $message, 'data' => $data], );
            die();
            // return ['message'=>'token不存在','code'=>'400'];
            // $this->redirect('api/errorHandle/error_response','code=400&message=token不存在');

        }

        $jwtAuth =JwtAuth::getInstance();
       
        exit();
        $res = $jwtAuth->setToken($token);

        if($jwtAuth->validate()&&$jwtAuth->verify()){
            /*此处getUid 为openid--之后根据业务逻辑修改getUid方法*/
            $openid = $this->jwtAuth->getUid();
            $userData = UserModel::where('openid','eq',$openid)->where('deleteTime is null')->order('createtime desc')->find();
            if( empty($userData) ){
                echo json_encode(["message"=>"用户不存在","code" => 400],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
                die();
            // $this->redirect('api/errorHandle/error_response','code=400&message=用户不存在'.$openid);
            }
            $this->user = $userData;
            $this->uid = $userData['id'];
        }else{
            echo json_encode(["message"=>"token已过期","code" => 400],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
            die();
        }
        /**
        // $openid = Session::get('Session_User_'.$token);
        if( empty($openid) ){
            echo json_encode(["message"=>urldecode("token已过期"),"code" => 400],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
            die();
            // $this->redirect('api/errorHandle/error_response','code=400&message=token已过期');
        }

        $userData = UserModel::where('openid','eq',$openid)->find();

        if( empty($userData) ){
            echo json_encode(["message"=>"用户不存在","code" => 400],JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
            die();
            // $this->redirect('api/errorHandle/error_response','code=400&message=用户不存在'.$openid);
        }
    
        
        $this->user = $userData;
        $this->uid = $userData->id;
    **/
    }

    //拦截请求的方法并设置请求头
    public function cross()
    {
        //header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); // 允许option，get，post请求
    
        header('Access-Control-Allow-Headers:x-requested-with,superuserid,content-type,x-token');
            // 允许x-requested-with请求头
        header('Access-Control-Allow-Credentials: true');

       

        // //获取请求参数
        // $data = $this->request->param();

        // //拦截请求地址并返回异常
        // if(in_array($data['method'], $this->certificationApi)){
        //     exception(Msg_ERR_PROOF,code_IS_NULL);
        // }
    }
    /**
     * 统计字段-and
     * @Author      GNLEON
     * @fun
     * @Param                   -
     * @DateTime    2020-07-10
     * @LastTime                2020-07-10
     * @copyright   [copyright]
     * @license     [license]
     * @param       [type]      $database  [数据库表明]
     * @param       string      $where     [查询条件]
     * @param       string      $field     [需要查询的字段]
     * @return      [type]                 [description]
     */
    public function total($database, $where = '', $field = '*')
    {
        $result = Db::name($database)
            ->where('deleteTime', 'NULL')
            ->where($where)
            ->count($field);
        return $result;
    }


    /**
     * 同total 此函数不需要过滤deleteTime为 NULL的条件 多用于视图查询(排行榜) 或 特殊情况(GroupBy)
     * @Author      GNLEON
     * @Param                   -
     * @DateTime    2020-07-10
     * @LastTime                2020-07-10
     * @copyright   [copyright]
     * @license     [license]
     * @param       [type]      $database  [数据库表明]
     * @param       string      $where     [查询条件]
     * @param       string      $field     [需要查询的字段]
     * @return      [type]                 [description]
     */
    public function totalView($database, $where = '', $field = '*')
    {
        $result = Db::name($database)
            ->where($where)
            ->count($field);
        return $result;
    }
    /**
     * [select 查询字段-and]
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:50:38+0800
     * @LastTime     2020-07-10T08:50:38+0800
     * @param        [type]                   $database [数据库表明]
     * @param        string                   $where    [查询条件]
     * @param        string                   $field    [需要查询的字段]
     * @param        integer                  $offset   [description]
     * @param        integer                  $length   [description]
     * @param        [type]                   $order    [description]
     * @return       [type]                             [description]
     */
    public function select($database, $where = '', $field = '', $offset = 0, $length = 500, $order = null)
    {
        $result = Db::name($database)
            ->where('deletetime', NULL)
            ->where($where)
            ->field($field)
            ->limit($offset, $length)
            ->order($order)
            ->select();
        return $result;
    }
    /**
     * [selectView 同select]  此函数不需要过滤deleteTime为 NULL的条件 多用于视图查询(排行榜) 或 特殊情况(GroupBy)
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:51:29+0800
     * @LastTime     2020-07-10T08:51:29+0800
     * @param        [type]                   $database [数据库表明]
     * @param        string                   $where    [查询条件]
     * @param        string                   $field    [需要查询的字段]
     * @param        integer                  $offset   [description]
     * @param        integer                  $length   [description]
     * @param        [type]                   $order    [description]
     * @return       [type]                             [description]
     */
    public function selectView($database, $where = '', $field = '', $offset = 0, $length = 500, $order = null)
    {
        $result = Db::name($database)
            ->where($where)
            ->field($field)
            ->limit($offset, $length)
            ->order($order)
            ->select();
        return $result;
    }
    /**
     * [find 查询一条字段]
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:53:05+0800
     * @LastTime     2020-07-10T08:53:05+0800
     * @param        [type]                   $database [数据库表明]
     * @param        string                   $where    [查询条件]
     * @return       [type]                             [description]
     */
    public function find($database, $where = '')
    {
        $result = Db::name($database)
            ->where($where)
            ->find();
        return $result;
    }
    /**
     * [insert 新增一条数据]
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:54:44+0800
     * @LastTime     2020-07-10T08:54:44+0800
     * @param        [type]                   $database [数据库表明]
     * @param        [type]                   $data     [插入数据]
     * @return       [type]                             [description]
     */
    public function insert($database, $data)
    {
        $result = Db::name($database)
            ->insert($data);
        // var_dump($result);
        if ($result)
            return $result;
        else {
            //To Do:错误异常捕捉
            return $this->jsonData(ApiErrDesc::ErrMsg_UPDATE[0], ApiErrDesc::ErrMsg_UPDATE[1]);
        }
    }
    /**
     * [insertGetId 新增一条数据返回id]
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:55:10+0800
     * @LastTime     2020-07-10T08:55:10+0800
     * @param        [type]                   $database [数据库表明]
     * @param        [type]                   $data     [插入数据]
     * @return       [type]                             [description]
     */
    public function insertGetId($database, $data)
    {
        
        $result = Db::name($database)
            ->insertGetId($data);
        // var_dump($result);
        if ($result)
            return $result;
        else {
            //To Do:错误异常捕捉
            return $this->jsonData(ApiErrDesc::ErrMsg_UPDATE[0], ApiErrDesc::ErrMsg_UPDATE[1]);
        }
    }
    /**
     * [insertAll 新增多条数据]
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:55:32+0800
     * @LastTime     2020-07-10T08:55:32+0800
     * @param        [type]                   $database [数据库表明]
     * @param        [type]                   $data     [插入数据]
     * @return       [type]                             [description]
     */
    public function insertAll($database, $data)
    {
        $result = Db::name($database)
            ->insertAll($data);
        // var_dump($result);
        if ($result)
            return true;
        else {
            //To Do:错误异常捕捉
            return $this->jsonData(ApiErrDesc::ErrMsg_INSERT[0], ApiErrDesc::ErrMsg_INSERT[1]);
        }
    }
    /**
     * [update 更新一条数据]
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-10T08:57:46+0800
     * @LastTime     2020-07-10T08:57:46+0800
     * @param        [type]                   $database [数据库表明]
     * @param        string                   $where    [更新条件]
     * @param        [type]                   $data     [插入数据]
     * @return       [type]                             [description]
     */
    public function update($database, $where = '', $data)
    {

        $result = Db::name($database)
            ->where($where)
            ->data($data)
            ->update();
        // var_dump($result);
        if ($result)
            return true;
        else {
            //To Do:错误异常捕捉
            return $this->jsonData(ApiErrDesc::ErrMsg_UPDATE[0], ApiErrDesc::ErrMsg_UPDATE[1]);
        }
    }
    /**
     * 工具类
     */
    
    /**
    * 验证手机号是否正确
    * @author honfei
    * @param number $mobile
    */
    function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
    /**
     * 生成订单号
     * Time: 11:15
     * @param $type 订单类型
     * @return string
     */
    function makeOrdersn($type='')
    {
        @date_default_timezone_set("PRC");
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = $type.date('YmdHis') . rand(10000000,99999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_id;
    }

    /**
     * 用户积分增减
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-17T09:00:24+0800
     * @LastTime     2020-11-17T09:00:24+0800
     * @param        [type]                       $openid     [description]
     * @param        [type]                       $points  [description]
     * @param        string                       $type    [description]
     *                                                     add增加 cut减少
     *                                            $just    A-默认(优先检测公司 不存在公司则是个人) M-不检测公司(个人) C-一定是公司   
     * @remark    待优化 个人 和 公司  类型的加减分       
     * @return       [type]                                [description]
     */
    public function member_integral($openid,$points,$type='add',$just='A'){
        $uinfo = $this->find('view_user','openid = "'.$openid.'"');
        $store_member = $this->find('store_member','openid = "'.$openid.'" and deletetime is null');
        if(!$store_member){return false;}
        // if($just!='A' || $just!='M'){return false;}
        if($points==0 || $points==NULL){return false;}
        switch ($type) {
            case 'add':
                if($uinfo['companyid'] && $uinfo['Interviewees'] ==1 && $just == 'A'){
                    $res = Db::table('store_member')->where('companyid = '.$uinfo['companyid'].' and deletetime is null')->setInc('frequency', $points);
                }else{
                    if($just=='C'){
                        $res = Db::table('store_member')->where('companyid = '.$uinfo['companyid'].' and deletetime is null')->setInc('frequency', $points);
                    }else{
                        $res = Db::table('store_member')->where('id', $store_member['id'])->setInc('frequency', $points);
                    }
                    
                }
                
                # code...
                break;
            case 'cut':
                if($uinfo['companyid'] && $uinfo['Interviewees'] ==1 && $just == 'A'){
                    $res = Db::table('store_member')->where('companyid = '.$uinfo['companyid'].' and deletetime is null')->setDec('frequency', $points);
                }else{
                    if($just=='C'){
                        $res = Db::table('store_member')->where('companyid = '.$uinfo['companyid'].' and deletetime is null')->setDec('frequency', $points);
                    }else{
                        $res = Db::table('store_member')->where('id', $store_member['id'])->setDec('frequency', $points);
                    }
                }
                break;
            default:
                return false;
                # code...
                break;
        }
        
        if($res){
            return true;
        }else{
            return false;
        }
    }
    
    
}